package cn.sstir.hackathon.core.csv;

import cn.sstir.hackathon.core.AbstractExportMap;
import com.univocity.parsers.csv.CsvFormat;
import com.univocity.parsers.csv.CsvWriter;
import com.univocity.parsers.csv.CsvWriterSettings;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * @author: fli
 * @email: fli@sstir.cn
 * @date: 2020/1/16 13:38
 */
public class CsvUtil {

    public static void exportCsv(Class<? extends AbstractExportMap> clazz,List<String> columns, List<Map<String,Object>> list, boolean quoteAllFields, String fileName, HttpServletResponse response) throws Exception{
        List<String> heads = new ArrayList<>();
        List<Object[]> data = new ArrayList<>();
        AbstractExportMap abstractExportMap = clazz.newInstance();
        for (String column : columns) {
            String columnName = abstractExportMap.get(column);
            if(columnName != null){
                heads.add(columnName);
            }
        }
        for (Map<String, Object> map : list) {
            List<Object> row = new ArrayList<>();
            for (String column : columns) {
                    row.add(map.get(column));
            }
            data.add(row.toArray(new Object[row.size()]));
        }
        exportCsv(quoteAllFields,heads.toArray(new String[heads.size()]),data,fileName,response);
    }

    /**
     * @param  heads 标题头
     * @param fileName  文件名
     * @param data 数据
     * @author fli
     * @date 2020/1/16 13:55
     */
    public static void exportCsv(boolean quoteAllFields, String[] heads, List<Object[]> data, String fileName, HttpServletResponse response) throws Exception {
        CsvWriterSettings settings = new CsvWriterSettings();
        settings.setQuoteAllFields(quoteAllFields);
        CsvFormat csvFormat = new CsvFormat();
        csvFormat.setDelimiter(',');
        settings.setFormat(csvFormat);
        settings.setIgnoreLeadingWhitespaces(false);
        settings.setIgnoreTrailingWhitespaces(false);
        settings.setHeaders(heads);
        response.setCharacterEncoding("UTF-8");
        response.setContentType("multipart/form-data");
        response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8")+".csv");
        OutputStream outputStream = response.getOutputStream();
        CsvWriter writer = new CsvWriter(new OutputStreamWriter(outputStream, "UTF-8"), settings);
        writer.writeHeaders();
        writer.writeRows(data);
        writer.close();
        try {
            outputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }


    }
}
